/*!
 * SystemsInfluenza.org Website v2.0
 * Copyright(c) 2006-2012 Institute for Systems Biology, Seattle, Washington, USA
 * codefor@systemsbiology.org
 * http://www.gnu.org/licenses/lgpl.html
 * Author: Hector Rovira
 * Description:  Draws a ExtJS grid based on a data matrix file (string labels, number values)
 */
DataGrid = Ext.extend(Object, {
    columnOrder: [],

    constructor: function(contentEl, url, primaryFields, agconfig, columnOrder) {
        this.contentEl = contentEl;
        this.primaryFields = primaryFields ? primaryFields : [];
        this.agconfig = agconfig ? agconfig : {};
        this.downloadUrl = url.replace("/query", "/contents");
        this.columnOrder = columnOrder;

        Ext.Ajax.request({
            url: url,
            method: "GET",
            params: {
                "tqx": "out:json_array"
            },
            success: this.load,
            scope: this
        });
    },

    load: function(response) {
        var fields = [];
        var data = [];

        var jsonArray = Ext.util.JSON.decode(response.responseText);
        if (jsonArray && jsonArray.length) {
            this.addColumnHeaders(jsonArray[0], fields);
            Ext.each(jsonArray, function(item) {
                this.addRow(item, fields, data);
            }, this);
        }

        var colModel = new Ext.grid.ColumnModel(fields);

        var gridConfig = Ext.apply({
            store: new Ext.data.ArrayStore({ fields: fields, data: data, id: Ext.id() }),
            colModel: colModel,
            stripeRows: true,
            columnLines: true,
            frame:true,
            collapsible: false,
            animCollapse: false,
            renderTo: this.contentEl,
            tbar: new Ext.Toolbar({
                items: [
                    {
                        text:"Select Columns",
                        menu: new ColumnSelectionMenu(colModel)
                    },
                    "-",
                    {
                        text: "Download Data",
                        handler: function() {
                            document.location = this.downloadUrl;
                        },
                        scope: this
                    }
                ]
            })
        }, this.agconfig);

        new Ext.grid.GridPanel(gridConfig);
    },

    addColumnHeaders: function(firstItem, fields) {
        var unorderedFields = {};

        Ext.each(this.primaryFields, function(primaryField) {
            if (firstItem.hasOwnProperty(primaryField)) {
                unorderedFields[primaryField] = this.createField(primaryField, true);
            }
        }, this);

        for (var key in firstItem) {
            if (firstItem.hasOwnProperty(key)) {
                if (this.primaryFields.indexOf(key) == -1) {
                    unorderedFields[key] = this.createField(key, false);
                }
            }
        }

        if (this.columnOrder) {
            Ext.each(this.columnOrder, function(col) {
                var fld = unorderedFields[col];
                if (fld) {
                    fields.push(fld);
                }
            });
        } else {
            for (var uf in unorderedFields) {
                var fld = unorderedFields[uf];
                if (fld) {
                    fields.push(fld);
                }
            }
        }
    },

    createField: function(key, isPrimary) {
        var headerId = Ext.id();
        return {
            id: headerId,
            name: headerId,
            dataIndex: headerId,
            sortable: true,
            originalKey: key,
            header: key.trim(),
            menuDisabled: true,
            isPrimary: isPrimary,
            width: 200
        };
    },

    addRow: function(item, fields, data) {
        var rowData = [];
        Ext.each(fields, function(f) {
            rowData[rowData.length] = item[f.originalKey];
        });
        data[data.length] = rowData;
    }
});

ColumnSelectionMenu = Ext.extend(Ext.menu.Menu, {
    constructor: function(columnModel) {
        this.id = Ext.id();
        this.columnModel = columnModel;

        ColumnSelectionMenu.superclass.constructor.call(this, {});

        this.on({
            scope     : this,
            beforeshow: this.beforeColMenuShow,
            itemclick : this.handleHdMenuClick
        });
    },

    beforeColMenuShow : function() {
        this.removeAll();

        Ext.each(this.columnModel.config, function(column) {
            if (!column.isPrimary) {
                this.add(new Ext.menu.CheckItem({
                    text       : column.header,
                    columnId   : column.id,
                    checked    : !column.hidden,
                    hideOnClick: false
                }));
            }
        }, this);
    },

    handleHdMenuClick: function(item) {
        var index = this.columnModel.getIndexById(item.columnId);
        this.columnModel.setHidden(index, item.checked);
    }
});
